package cn.rokhdelar.ams.common.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.rokhdelar.ams.common.domain.vo.AttachmentVO;
import cn.rokhdelar.ams.common.service.AttachmentService;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 附件控制器
 * @author Rokhdelar
 * @since 2025/3/14 -- 15:23
 **/
@Controller
@RequestMapping("/attachments")
@Schema(description = "附件控制器")
@RequiredArgsConstructor
public class AttachmentController {
    private final AttachmentService attachmentService;

    @Schema(description = "多文件上传接口")
    @PostMapping(value = "/uploads")
    public ResponseEntity<List<AttachmentVO>> upload(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(value = "remark", defaultValue = "") String remark) {
        return ResponseEntity.ok(attachmentService.uploads(files, remark));
    }

    @Schema(description = "单文件上传接口")
    @PostMapping(value = "/upload")
    public ResponseEntity<AttachmentVO> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "remark", defaultValue = "") String remark) {
        return ResponseEntity.ok(attachmentService.upload(file, remark));
    }

    @Schema(description = "附件信息查询接口")
    @GetMapping(value = "/{id}")
    public ResponseEntity<AttachmentVO> getAttachment(@PathVariable String id) {
        return ResponseEntity.ok(BeanUtil.copyProperties(attachmentService.getById(id), AttachmentVO.class));
    }

    @Schema(description = "附件下载接口")
    @GetMapping(value = "/download/{id}")
    public ResponseEntity<Resource> download(@PathVariable String id) {
        Resource resource = attachmentService.download(id);
        String headerValue = "attachment; filename=\"" + resource.getFilename() + "\"";
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
                .body(resource);
    }

    @Schema(description = "附件删除接口， 根据id删除附件信息，同时也会删除对应的文件信息")
    @DeleteMapping(value = "/delete/{id}")
    public ResponseEntity<Boolean> delete(@PathVariable String id) {
        return ResponseEntity.ok(attachmentService.delete(id));
    }

}
